package com.usian.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.dtos.UserSearchDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.search.feign.BehaviorFeign;
import com.usian.search.service.ApArticleSearchService;
import com.usian.search.service.ApUserSearchService;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ApArticleSearchServiceImpl implements ApArticleSearchService{

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ApUserSearchService apUserSearchService;

    @Autowired
    private BehaviorFeign behaviorFeign;

    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {


        //第一次搜索的时候保存搜索记录

        if(dto.getFromIndex() == 0){
            ApUser user = AppThreadLocalUtils.getUser();
            ApBehaviorEntry apBehaviorEntry = behaviorFeign.findByUserIdOrEntryId(user.getId(), dto.getEquipmentId());
            if(apBehaviorEntry ==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            apUserSearchService.insert(apBehaviorEntry.getId(),dto.getSearchWords());
        }


        SearchRequest searchRequest =new SearchRequest("app_info_article");
        SearchSourceBuilder searchSourceBuilder =new SearchSourceBuilder();

        BoolQueryBuilder boolQueryBuilder =new BoolQueryBuilder();

        //QueryStringQueryBuilder 在多个字段之间查询
        QueryStringQueryBuilder queryStringQueryBuilder= QueryBuilders
                .queryStringQuery(dto.getSearchWords()).field("title").field("content").defaultOperator(Operator.OR);

        boolQueryBuilder.must(queryStringQueryBuilder);

        //RangeQueryBuilder 时间区间查询   where （title=？or content=？）and publishtime<?
        RangeQueryBuilder rangeQueryBuilder =QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime());
        boolQueryBuilder.filter(rangeQueryBuilder);

        searchSourceBuilder.query(boolQueryBuilder);

        //结果排序
        searchSourceBuilder.sort("publishTime", SortOrder.DESC);

        //分页
        searchSourceBuilder.from(dto.getPageNum());
        searchSourceBuilder.size(dto.getPageSize());

        searchRequest.source(searchSourceBuilder);
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);


        SearchHit[] hits = response.getHits().getHits();
        List<Map> articleList = new ArrayList<>();
        for(SearchHit hit:hits){
            String sourceAsString = hit.getSourceAsString(); //es得到结果后以string类型返回
            System.out.println(sourceAsString);

            Map map = JSON.parseObject(sourceAsString, Map.class);
            articleList.add(map);
        }
        return ResponseResult.okResult(articleList);
    }
}
